package com.salt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.salt.entity.IdleAffiliateCpaIncomeDetail;
import com.salt.mapper.IdleAffiliateCpaIncomeDetailMapper;
import com.salt.service.IdleAffiliateCpaIncomeDetailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Service
@RequiredArgsConstructor
public class IdleAffiliateCpaIncomeDetailServiceImpl extends ServiceImpl<IdleAffiliateCpaIncomeDetailMapper, IdleAffiliateCpaIncomeDetail> implements IdleAffiliateCpaIncomeDetailService {

    private final ObjectMapper objectMapper;

    @Override
    public Page<IdleAffiliateCpaIncomeDetail> pageQuery(Page<IdleAffiliateCpaIncomeDetail> page, Date startDate, Date endDate, Integer state, String keyword, String inviteCode) {
        LambdaQueryWrapper<IdleAffiliateCpaIncomeDetail> wrapper = new LambdaQueryWrapper<>();
        
        // 添加日期范围条件
        if (startDate != null && endDate != null) {
            wrapper.between(IdleAffiliateCpaIncomeDetail::getCreateTime, startDate, endDate);
        }
        wrapper.eq(IdleAffiliateCpaIncomeDetail::getSubPublisherId,inviteCode);
        wrapper.ne(IdleAffiliateCpaIncomeDetail::getState, 3);
        
        // 添加关键词搜索条件
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.and(w -> w
                .like(IdleAffiliateCpaIncomeDetail::getBillId, keyword)
                .or()
                .like(IdleAffiliateCpaIncomeDetail::getComment, keyword)
            );
        }
        
        // 按创建时间倒序排序
        wrapper.orderByDesc(IdleAffiliateCpaIncomeDetail::getCreateTime);
        
        return page(page, wrapper);
    }

    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getIncomeSummary(Date startDate, Date endDate, String inviteCode) {
        log.info("开始统计CPA佣金明细汇总数据，时间范围：{} 至 {}", startDate, endDate);
        
        Map<String, Object> result = new HashMap<>();
        AtomicInteger u2UserCount = new AtomicInteger(0);
        AtomicInteger newUserCount = new AtomicInteger(0);
        AtomicInteger newFriendCount = new AtomicInteger(0);
        AtomicInteger oldFriendCount = new AtomicInteger(0);
        AtomicReference<BigDecimal> totalAmount = new AtomicReference<>(BigDecimal.ZERO);
        
        try {
            // 构建查询条件
            LambdaQueryWrapper<IdleAffiliateCpaIncomeDetail> wrapper = new LambdaQueryWrapper<>();
            if (startDate != null && endDate != null) {
                wrapper.between(IdleAffiliateCpaIncomeDetail::getCreateTime, startDate, endDate);
            }
            wrapper.ne(IdleAffiliateCpaIncomeDetail::getState, 3);
            wrapper.eq(IdleAffiliateCpaIncomeDetail::getSubPublisherId,inviteCode);
            // 查询所有符合条件的记录
            list(wrapper).forEach(detail -> {
                try {
                    // 解析extend_info字段
                    if (detail.getExtendInfo() != null) {
                        JsonNode extendInfo = objectMapper.readTree(detail.getExtendInfo());
                        if (extendInfo.has("user_l1_label") && "U2".equals(extendInfo.get("user_l1_label").asText())) {
                            u2UserCount.incrementAndGet();
                        }
                    }
                    
                    // 统计推荐新用户数量
                    if ("推荐新用户".equals(detail.getComment())) {
                        newUserCount.incrementAndGet();
                    }
                    
                    // 统计推荐新朋友购买数量
                    if ("推荐新朋友购买".equals(detail.getComment())) {
                        newFriendCount.incrementAndGet();
                    }
                    if (detail.getComment().contains("推荐老朋友") &&!detail.getComment().contains("U2")) {
                        oldFriendCount.incrementAndGet();
                    }
                    
                    // 累加总金额
                    if (detail.getAmount() != null) {
                        totalAmount.updateAndGet(current -> current.add(detail.getAmount()));
                    }
                } catch (Exception e) {
                    log.error("处理CPA佣金明细数据失败，billId: {}", detail.getBillId(), e);
                }
            });
            
            // 设置结果
            result.put("u2UserCount", u2UserCount.get());
            result.put("newUserCount", newUserCount.get());
            result.put("newFriendCount", newFriendCount.get());
            result.put("totalAmount", totalAmount.get());
            result.put("oldFriendCount", oldFriendCount.get());
            
            log.info("CPA佣金明细汇总数据统计完成：{}", result);
        } catch (Exception e) {
            log.error("统计CPA佣金明细汇总数据失败", e);
            throw new RuntimeException("统计CPA佣金明细汇总数据失败", e);
        }
        
        return result;
    }
} 